package org.example.api;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.Optional;

public class WeatherAPIImpl implements WeatherAPI {
    private WeatherClient provinceClient;
    private WeatherClient cityClient;
    private WeatherClient countyClient;
    private WeatherClient weatherClient;

    public WeatherAPIImpl(int retryCount, int timeout) {
        provinceClient = new WeatherClient("http://www.weather.com.cn/data/city3jdata/china.html", retryCount, timeout, 5);
        cityClient = new WeatherClient("http://www.weather.com.cn/data/city3jdata/provshi/{code}.html", retryCount, timeout, 5);
        countyClient = new WeatherClient("http://www.weather.com.cn/data/city3jdata/station/{code}.html", retryCount, timeout, 5);
        weatherClient = new WeatherClient("http://www.weather.com.cn/data/sk/{code}.html", retryCount, timeout, 5);
    }

    /**
     * fetch and return the temperature of one certain county in China
     * @param province
     * @param city
     * @param county
     * @return
     */
    @Override
    public Optional<Integer> getTemperature(String province, String city, String county) {
        if(StrUtil.hasBlank(province, city, county)){
            throw new IllegalArgumentException("parameter province/city/country must not be null");
        }
        //province code + city code + county code
        StringBuilder fullCode = new StringBuilder();
        Optional<String> code = provinceClient.findCodeByName(null, province);
        if(code.isPresent()){
            fullCode.append(code.get());
            code = cityClient.findCodeByName(fullCode.toString(), city);
        }
        if(code.isPresent()){
            fullCode.append(code.get());
            code = countyClient.findCodeByName(fullCode.toString(), county);
        }
        if(code.isPresent()){
            fullCode.append(code.get());
        }else{
            return Optional.empty();
        }
        JSONObject json = weatherClient.getJSON(fullCode.toString());
        JSONObject weatherInfo = json.getJSONObject("weatherinfo");
        if(weatherInfo != null){
            Double temp1 = weatherInfo.getObject("temp", Double.class);
            Integer temp = null;
            if(temp1 != null){
                temp = temp1.intValue();
            }
            return Optional.of(temp);
        }
        return Optional.empty();
    }



}
